<template>
  <div>
    <div class="pageTitleWhole">
      <div style="overflow: hidden">
        <a style="margin-right: 20px; margin-bottom: 15px; float: left;">
          <router-link
            :to="`/financialCenter/${page.isPayOrRecevie?'payableBillOfHuaJzx':'receivableBillOfHuaJzx'}?f=1`"
          >
            <a-icon type="left" />返回
          </router-link>
        </a>
        <a-breadcrumb>
          <a-breadcrumb-item>
            <router-link :to="`/financialCenter/${page.url}`">应{{page.isPayOrRecevie?'付':'收'}}账单</router-link>
          </a-breadcrumb-item>
          <a-breadcrumb-item>账单详情</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
    </div>
    <div class="pageContentWhole">
      <a-row>
        <a-col :span="24">
          <a-form layout="inline">
            <a-form-item label="结算对象">
              <a-input v-model="searchForm.custName" />
            </a-form-item>
            <a-form-item label="公司编号/运单号/箱号">
              <a-input v-model="searchForm.orderCodeOrContainerNo" />
            </a-form-item>
            <a-form-item label="船名/航次">
              <a-input v-model="searchForm.shipNameOrVoyage" />
            </a-form-item>
            <a-form-item label="结算类型">
              <a-select v-model="searchForm.settlementType" class="selectWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in settlementTypeList" :key="v.key">{{v.value}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="所属部门">
              <a-tree-select
                class="selectInputWidth"
                v-model="searchForm.deptId"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :load-data="onLoadData"
                :tree-data="deptTreeData"
                placeholder="请选择"
                @change="onChangeTree"
              ></a-tree-select>
            </a-form-item>
            <a-form-item label="所属销售">
              <a-select v-model="searchForm.sellerId" class="selectInputWidth">
                <a-select-option v-for="v in sellers" :key="v.uiId">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-input-group compact>
                <a-select v-model="searchForm.timeType" class="selectWidth">
                  <a-select-option v-for="(v) in dateOptions" :key="v.key">{{v.title}}</a-select-option>
                </a-select>
                <a-range-picker @change="onDateChange">
                  <a-icon slot="suffixIcon" type="calendar" />
                </a-range-picker>
              </a-input-group>
            </a-form-item>
            <a-form-item label="订单类型">
              <a-select v-model="searchForm.orderType" class="selectInputWidth">
                <a-select-option key>全部</a-select-option>
                <a-select-option v-for="v in OrderOptions" :key="v.key">{{v.title}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="费用类型">
              <a-select v-model="searchForm.feeTypeId" class="selectInputWidth">
                <a-select-option value>请选择</a-select-option>
                <a-select-option v-for="(v,k) in feeList" :key="k" :value="v.id">{{v.name}}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="发票号">
              <a-input v-model="searchForm.invoiceNo" />
            </a-form-item>
            <a-form-item label="付款银行">
              <a-input v-model="searchForm.transactionBank" />
            </a-form-item>

            <a-form-item>
              <a-button type="primary" @click="setViewFields">设置查看字段</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="handleSubmit1">查询</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="exportExcel">导出Excel</a-button>
            </a-form-item>
            <a-form-item v-if="page.status === '1'">
              <a-button type="primary" @click="removeBills">移出账单</a-button>
            </a-form-item>
          </a-form>
        </a-col>

        <a-col :span="24" style="margin-top:24px;">
          <a-table
            :row-selection="page.status === '1'?{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange}:null"
            :columns="columns"
            :loading="loading"
            :data-source="tableData"
            :pagination="pagination"
            :scroll="scroll"
            row-key="id"
          >
            <template slot="rn" slot-scope="text, record, index">{{index + 1}}</template>
            <template slot="code" slot-scope="text, record">
              <a @click="toCompanyCode(record.businessId)">{{text}}</a>
            </template>
          </a-table>
        </a-col>
      </a-row>
    </div>

    <!-- 设置查看字段 -->
    <a-modal
      :visible="fieldVisible"
      title="设置查看字段"
      centered
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-checkbox-group @change="onCheckChange" :defaultValue="defaultValues">
        <a-row>
          <a-col v-for="(box, i) in fields" :key="i" :span="12" style="margin-bottom:3px;">
            <a-checkbox :value="box.key">{{box.value}}</a-checkbox>
          </a-col>
        </a-row>
      </a-checkbox-group>
    </a-modal>
  </div>
</template>

<script>
import { mixin } from '@/common/common'
import store from 'store'
import { queryFeeTypeList, querySellerDown, queryDeptDown } from '@/api'
import { commonExport } from '@/api/request'
import { queryJHOrderBillCostList, cancelFromBill } from '@/api/financialCenter'

const dateOptions = [
  { key: 1, title: '订单创建时间' },
  { key: 2, title: '装货时间' },
  { key: 3, title: '费用产生时间' }
]
// 订单类型
const OrderOptions = [
  { key: 'DOMESTIC_TRADE_EXPORTS', title: '内贸出口订单' },
  { key: 'DOMESTIC_TRADE_IMPORTS', title: '内贸进口订单' },
  { key: 'FOREIGN_TRADE_EXPORTS', title: '外贸出口订单' },
  { key: 'FOREIGN_TRADE_IMPORTS', title: '外贸进口订单' },
  { key: 'UNITED_TRANSPORT_EXPORTS', title: '联运出口订单' },
  { key: 'UNITED_TRANSPORT_IMPORTS', title: '联运进口订单' }
]
const defaultSearchForm = (feeType, billId) => ({
  feeType,
  billId,
  status: '',
  custName: '',
  feeTypeId: '',
  settlementType: '',
  sellerId: '', // 销售id
  deptId: null, // 销售所属部门id
  orderType: '',
  timeType: 1,
  searchStartTime: null,
  searchEndTime: null,
  dateRange: [null, null],
  invoiceNo: '', // 发票号
  transactionBank: '' // 付款银行
})

const deptData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL'
}
const sellerData = {
  type: 2, // type 1判断权限 2不判断
  dataRole: 'CONTAINER_SELL',
  status: 1
}

export default {
  props: ['id'],
  mixins: [mixin],
  data () {
    const columnsWhole = [
      {
        title: '序号',
        width: 60,
        scopedSlots: { customRender: 'rn' }
      },
      {
        title: '公司编号',
        dataIndex: 'shipOrderCode',
        scopedSlots: { customRender: 'code' }
      },
      {
        title: '运单号',
        dataIndex: 'seagoingShipOrderCode',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '箱号',
        dataIndex: 'containerNo',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '结算对象',
        dataIndex: 'custName'
      },
      {
        title: '箱型箱量',
        dataIndex: 'containerType',
        customRender: (text, record, index) => {
          return `${text}*1`
        }
      },
      {
        title: '费用类型',
        dataIndex: 'feeName'
      },
      {
        title: '订单创建日期',
        dataIndex: 'orderCreateTime'
      },
      {
        title: '费用产生日期',
        dataIndex: 'costTime'
      },
      {
        title: '金额（元）',
        dataIndex: 'amount',
        customRender: (text, record, index) => {
          return record.currencyType === 'USD' ? <span class='t_money t_money1'>$ {text}</span> : text
        }
      },
      {
        title: '状态',
        dataIndex: 'status',
        customRender: (text, record, index) => {
          return text === 1 ? <span style="color: red">未对账</span> : (text === 2 ? <span style="color: green">已对账</span> : (text === 3 ? '已结清' : ''))
        },
        _needName: true
      },
      {
        title: '发票号',
        dataIndex: 'invoiceNo',
        width: 150,
        ellipsis: true,
        customRender: (text, record, index) => {
          return record.status === 3 ? text : '--'
        }
      },
      {
        title: '开票时间',
        dataIndex: 'lastInvoiceDate',
        customRender: (text, record, index) => {
          return record.status === 3 ? text : '--'
        }
      },
      {
        title: '付款银行',
        dataIndex: 'transactionBank',
        width: 150,
        ellipsis: true,
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '销售人员',
        dataIndex: 'sellerName'
      },
      {
        title: '操作人员',
        dataIndex: 'handlerName'
      },
      {
        title: '订单类型',
        dataIndex: 'orderType',
        customRender: (text, record, index) => {
          const t = OrderOptions.filter(v => v.key === text)[0]
          return t ? t.title : '--'
        },
        _needName: true
      },
      {
        title: '结算类型',
        dataIndex: 'settlementType',
        customRender: (text, record, index) => {
          return this.checkSettlementTypeName(text)
        },
        _needName: true
      },
      {
        title: '运输条款',
        dataIndex: 'transportTerms'
      },
      {
        title: '货名',
        dataIndex: 'goodsName',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '货重（吨）',
        dataIndex: 'goodsWeight',
        customRender: (text, record, index) => {
          return text || '--'
        }
      },
      {
        title: '装货时间',
        dataIndex: 'loadTime'
      },
      {
        title: '始发港',
        dataIndex: 'startPortName'
      },
      {
        title: '目的港',
        dataIndex: 'endPortName'
      },
      {
        title: '驳船船名航次',
        dataIndex: 'shipName',
        customRender: (text, record, index) => {
          return text ? `${text}/${record.voyageNumber}` : '--'
        }
      },
      {
        title: '海船船名航次',
        dataIndex: 'seagoingShipName',
        customRender: (text, record, index) => {
          return text ? `${text}/${record.seagoingShipVoyage}` : '--'
        }
      }
    ]

    return {
      // 页面区分信息
      page: {
        status: '', // 1未结清，2已结清
        url: '',
        isPayOrRecevie: true // t付 f收
      },
      dateOptions,
      OrderOptions,
      feeList: [],
      searchForm: {},
      deptTreeData: [],
      sellers: [],
      columnsWhole,
      columns: [],
      scroll: { x: '250%' },
      loading: false,
      tableData: [],
      pagination: {},
      pageNum: 1,
      pageSize: 10,
      // 设置查看字段
      fieldVisible: false,
      fields: [],
      defaultValues: [],
      currentValues: null,
      selectedRowKeys: []
    }
  },
  methods: {
    initFeeTypeRequest (e) {
      queryFeeTypeList(e)
        .then(res => {
          this.feeList = res.data
        })
        .catch(rs => { })
    },
    onLoadData (treeNode) {
      return new Promise(resolve => {
        if (treeNode.dataRef.children && treeNode.dataRef.children.length > 0) {
          resolve()
          return
        }
        queryDeptDown({ parentId: treeNode.dataRef.key, ...deptData }).then(rsp => {
          let childrenData = []
          rsp.data.forEach((value) => {
            childrenData.push({
              title: value.name,
              key: value.deptId,
              value: value.deptId
            })
          })
          treeNode.dataRef.children = childrenData
          this.deptTreeData = [...this.deptTreeData]
          resolve()
        })
      })
    },
    initDept (e) {
      queryDeptDown(e).then(rsp => {
        let initData = []
        rsp.data.forEach((value, index) => {
          initData.push({
            title: value.name,
            key: value.deptId,
            value: value.deptId
          })
        })
        this.deptTreeData = initData
      })
    },
    onChangeTree (value) {
      this.initSellerDown(value)
    },
    initSellerDown (deptId) {
      querySellerDown({ ...sellerData, deptId }).then(rsp => {
        this.sellers = rsp.data.map((v, i) => {
          if (!v.uiId) {
            v.name = '请选择'
            v.uiId = ''
          }
          return v
        })
      })
    },
    onDateChange (date, dataStr) {
      this.searchForm.searchStartTime = dataStr[0]
      this.searchForm.searchEndTime = dataStr[1]
      this.searchForm.dateRange = [date[0], date[1]]
    },
    handleSubmit1 () {
      this.pageNum = 1
      this.handleSubmit()
    },
    handleSubmit () {
      this.selectedRowKeys = []
      this.loading = true
      queryJHOrderBillCostList({
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize
      }).then(rsp => {
        this.loading = false
        this.tableData = rsp.data.list
        this.pagination = {
          current: this.pageNum,
          pageSize: rsp.data.pageSize,
          total: rsp.data.total,
          showQuickJumper: false,
          showSizeChanger: true,
          showTotal: total => `共${total}条记录 第${this.pageNum}/${rsp.data.pages}页`,
          onChange: pageNum => {
            this.pageNum = pageNum
            this.handleSubmit()
          },
          onShowSizeChange: (current, size) => {
            this.pageNum = current
            this.pageSize = size
            this.handleSubmit()
          }
        }
      })
    },
    setViewFields () {
      this.fields = this.columnsWhole.map(v => {
        if (v.dataIndex) {
          return {
            key: v.dataIndex,
            value: v.title
          }
        }
      }).filter(v => v)
      this.fieldVisible = true
    },
    onCheckChange (checkedValues) {
      this.currentValues = checkedValues
    },
    handleOk () {
      this.defaultValues = this.currentValues
      store.set('jzx', this.currentValues)
      this.columns = this.columnsWhole.filter((v, i) => {
        return i === 0 || this.currentValues.includes(v.dataIndex)
      })
      this.scroll.x = 150 * this.columns.length
      this.fieldVisible = false
    },
    handleCancel () {
      this.fieldVisible = false
    },
    exportExcel () {
      commonExport('/bill/exportJHOrderBillCostList', {
        ...this.searchForm,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        columns: this.columnsWhole
      })
    },
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    removeBills () {
      if (!this.$root._bc.removeBill) {
        this.$message.error('您无此权限！')
        return
      }
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请先选择费用明细')
      } else {
        cancelFromBill({
          billCostIds: this.selectedRowKeys,
          billId: this.id
        }).then(rsp => {
          this.$message.success('移除成功')
          this.handleSubmit()
        })
      }
    },
    toCompanyCode (businessId) {
      window.open(`/orderCenter/order/detail/${businessId}`, '_blank')
    }
  },
  created () {
    const url = this.$route.meta.selectKeyUrl
    this.page.url = url
    this.page.isPayOrRecevie = !!~url.indexOf('pay')

    let feeType = this.page.isPayOrRecevie ? 2 : 1
    this.searchForm = defaultSearchForm(feeType, this.id)

    this.page.status = this.$route.query.status + ''

    // 费用类型
    this.initFeeTypeRequest({
      status: 1,
      belongCompany: 'JIA_HUA',
      feeType
    })

    // 所属部门
    this.initDept(deptData)
    // 所属销售
    this.initSellerDown()

    // 读取设置的可见字段
    this.currentValues = this.defaultValues = this.currentValues || store.get('jzx') || this.columnsWhole.map(v => v.dataIndex).filter(v => v)
    this.columns = this.columnsWhole.filter((v, i) => {
      return i === 0 || this.currentValues.includes(v.dataIndex)
    })
    this.scroll.x = 150 * this.columns.length
  },
  mounted () {
    this.handleSubmit()
  }
}
</script>

<style lang="less" scoped>
</style>
